/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        int n = 0;
        ListNode* cur = head;
        while(cur)
        {
            cur = cur->next;
            ++n;
        }
        n /= k;
 
        cur = head;
        ListNode* newHead = new ListNode();
        ListNode* prev = newHead;
        while(n--)
        {
            ListNode* tmp = cur;
            int cnt = k;
            while(cnt--)
            {
                ListNode* prevNext = cur->next;
                cur->next = prev->next; // cur头插到prev
                prev->next = cur;
                cur = prevNext;
            }
            prev = tmp;
        }
        prev->next = cur;
        cur = newHead->next;
        delete newHead;
        return cur;
    }
};